package com.hengtiansoft.lfy.chart.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.hengtiansoft.lfy.activity.LoginActivityV2;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.base.BaseFragment;
import com.hengtiansoft.lfy.chart.activity.AddContactSearchActivity;
import com.hengtiansoft.lfy.chart.activity.ContactlistActivity;
import com.hengtiansoft.lfy.chart.activity.GroupPickContactsActivity;
import com.hengtiansoft.lfy.chart.activity.GroupsActivity;
import com.hengtiansoft.lfy.chart.activity.PersonalDetailsActivity;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.hengtiansoft.lfy.chart.applib.utils.HXPreferenceUtils;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.action.ContactListJson;
import com.hengtiansoft.lfy.chart.action.GetUserJson;
import com.hengtiansoft.lfy.chart.activity.ChatActivity;
import com.hengtiansoft.lfy.activity.MainActivity;
import com.hengtiansoft.lfy.chart.adapter.ChatAllHistoryAdapter;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.chart.bean.Friends;
import com.hengtiansoft.lfy.chart.bean.getGroupAvatarByUsernameBean;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.chart.db.InviteMessgeDao;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.chart.domain.FriendsUser;
import com.hengtiansoft.lfy.chart.domain.InviteMessage;
import com.hengtiansoft.lfy.chart.domain.InviteMessage.InviteMesageStatus;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.utils.CommonUtils;
import com.hengtiansoft.lfy.chart.utils.GuideViewUtil;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.utils.Utils;
import com.hengtiansoft.lfy.widget.MyPopupWindow;
import com.hengtiansoft.lfy.widget.MyPopupWindow.OnDismiss;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMGroupChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMContactManager;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.HanziToPinyin;
import com.hyphenate.util.NetUtils;
import com.karics.library.zxing.android.CaptureActivity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: ChatAllHistoryActivity
 * @Description: 显示所有会话记录，比较简单的实现，更好的可能是把陌生人存入本地，这样取到的聊天记录是可控的
 * @author caijiajun
 * @date 2015年11月19日 上午9:53:19
 * 
 */
public class ChatAllHistoryFragment extends BaseFragment
        implements View.OnClickListener,EMMessageListener {
    private static final String TAG = "ChatAllHistoryActivity";
    private InputMethodManager inputMethodManager;
    private ListView listView;
    private ChatAllHistoryAdapter adapter;
    private LinearLayout mLlHint;
    private EditText query;
    private ImageButton clearSearch;
    public RelativeLayout errorItem;
    private MyPopupWindow mPopupWindow;
    private View mWindowView;
    public TextView errorText;
    private boolean hidden;
    private List<EMConversation> conversationList = new ArrayList<EMConversation>();
    private ImageView mIvBack;
    private ImageView mIvMore;
    private ImageView mIvContacts;
    private Context mContext;
    public RelativeLayout mRlAddGroup;
    public LinearLayout mLlAddFriends;
    public LinearLayout mLlScan;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;
    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;
    // 账号在别处登录
    public boolean isConflict = false;
    private MyConnectionListener connectionListener = null;
    private int currentTabIndex;
    private GuideViewUtil mGuideViewUtil;
    private InviteMessgeDao inviteMessgeDao;
    private UserDao userDao;
    private MyGroupChangeListener groupChangeListener = null;
    private static final int REQUEST_CODE_SCAN = 0x0000;
    private static final String DECODED_CONTENT_KEY = "codedContent";
    private static final String DECODED_BITMAP_KEY = "codedBitmap";

    /**
     * 检查当前用户是否被删除
     */
    public boolean getCurrentAccountRemoved() {
        return isCurrentAccountRemoved;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_conversation_history, container, false);
    }
    private boolean hideEnter = false;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        initView();
        getView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                getView().getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight =  getView().getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight < 300) {
                    if(hideEnter) {
                        getView().requestFocus();
                        hideEnter=false;
                    }
                }else{

                    hideEnter=true;
                }
            }
        });
    }

    private void initView() {
        inputMethodManager = (InputMethodManager) mContext.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        errorItem = (RelativeLayout) getView().findViewById(R.id.rl_error_item);
        errorText = (TextView) errorItem.findViewById(R.id.tv_connect_errormsg);
        errorItem.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(errorText.getText().toString().equals(getActivity().getString(R.string.not_login_title))){
                    startActivity(
                            new Intent(mContext, LoginActivityV2.class));
                }
            }
        });
        mLlHint = (LinearLayout) getView().findViewById(R.id.ll_hint);
        conversationList.addAll(loadConversationsWithRecentChat());
        mIvMore = (ImageView) getView().findViewById(R.id.iv_more);
        mIvContacts = (ImageView) getView().findViewById(R.id.iv_contacts);
        listView = (ListView) getView().findViewById(R.id.list);
        adapter = new ChatAllHistoryAdapter(mContext, 1, conversationList);
        // 设置adapter
        listView.setAdapter(adapter);
        inviteMessgeDao = new InviteMessgeDao(mContext);
        userDao = new UserDao(mContext);
        GetUserJson getUserJson = new GetUserJson(
                Config.getUserToken(),
                Config.getUserName());
        getGroupAvatarRequest(Constants.getAllGroup, getUserJson);
        final String st2 = getResources()
                .getString(R.string.Cant_chat_with_yourself);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                if(!Config.isUserLogined()){
                    startActivity(new Intent(getActivity(),
                            LoginActivityV2.class));
                    return;
                }
                EMConversation conversation = adapter.getItem(position);
                String username = conversation.conversationId();
                if (username.equals(Config.getUserName()))
                    Toast.makeText(mContext, st2, 0).show();
                else {
                    // 进入聊天页面
                    Intent intent = new Intent(mContext, ChatActivity.class);
                    if (conversation.isGroup()) {
                        if (conversation
                                .getType() == EMConversation.EMConversationType.ChatRoom) {
                            // it is group chat
                            intent.putExtra("chatType",
                                    ChatActivity.CHATTYPE_CHATROOM);
                            intent.putExtra("groupId", username);
                        } else {
                            // it is group chat
                            intent.putExtra("chatType",
                                    ChatActivity.CHATTYPE_GROUP);
                            intent.putExtra("groupId", username);
                        }

                    } else {
                        // it is single chat
                        intent.putExtra("userId", username);
                    }
                    startActivity(intent);
                }
            }
        });
        // 注册上下文菜单
        registerForContextMenu(listView);

        listView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 隐藏软键盘
                hideSoftKeyboard();
                return false;
            }

        });
        // 搜索框
        query = (EditText) getView().findViewById(R.id.query);
        String strSearch = getResources().getString(R.string.search);
        // 搜索框中清除button
        clearSearch = (ImageButton) getView().findViewById(R.id.search_clear);
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                adapter.getFilter().filter(s);
                if (s.length() > 0) {
                    mLlHint.setVisibility(View.GONE);
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    mLlHint.setVisibility(View.VISIBLE);
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });
        mIvBack = (ImageView) getView().findViewById(R.id.iv_back);
        mIvBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext,
                        MainActivity.class));
            }
        });
        setListener();
        initBox();
        init();
    }



    private void init() {
        // setContactListener监听联系人的变化等
        // EMContactManager.getInstance().setContactListener(
        // new MyContactListener());
        // 注册一个监听连接状态的listener
        connectionListener = new MyConnectionListener();
        EMClient.getInstance().addConnectionListener(connectionListener);

        // groupChangeListener = new MyGroupChangeListener();
        // // 注册群聊相关的listener
        // EMGroupManager.getInstance()
        // .addGroupChangeListener(groupChangeListener);

    }



    /**
     * MyGroupChangeListener
     */
    public class MyGroupChangeListener implements EMGroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName,
                                         String inviter, String reason) {

            boolean hasGroup = false;
            for (EMGroup group : EMClient.getInstance().groupManager().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = getResources()
                    .getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage
                    .createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(inviter + " " + st3));
            // 保存邀请消息
           // EMChatManager.getInstance().saveMessage(msg);
            EMClient.getInstance().chatManager().sendMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    // updateUnreadLabel();
                    // 刷新ui
                    // if (currentTabIndex == 0)
                    refresh();
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onInvitationAccepted(String groupId, String inviter,
                                        String reason) {

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee,
                                         String reason) {

        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {

            // 提示用户被T了，demo省略此步骤
            // 刷新ui
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        if (CommonUtils.getTopActivity(mContext)
                                .equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        EMLog.e(TAG, "refresh exception " + e.getMessage());
                    }
                }
            });
        }

        @Override
        public void onGroupDestroyed(String groupId, String groupName) {

            // 群被解散
            // 提示用户群被解散,demo省略
            // 刷新ui
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onAutoAcceptInvitationFromGroup(String groupId, String groupName,
                                                    String inviter) {
            boolean hasGroup = false;
            for (EMGroup group : EMClient.getInstance().groupManager().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            String st3 = getResources()
                    .getString(R.string.Invite_you_to_join_a_group_chat);
            EMMessage msg = EMMessage
                    .createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(inviter + " " + st3));
            // 保存邀请消息
            // EMChatManager.getInstance().saveMessage(msg);
            EMClient.getInstance().chatManager().sendMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    // updateUnreadLabel();
                    // 刷新ui
                    // if (currentTabIndex == 0)
                    refresh();
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onRequestToJoinReceived(String groupId, String groupName,
                                          String applyer, String reason) {

            // 用户申请加入群聊
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " 申请加入群聊：" + groupName);
            msg.setStatus(InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
        }

        @Override
        public void onRequestToJoinAccepted(String groupId, String groupName,
                                        String accepter) {

            String st4 = getResources()
                    .getString(R.string.Agreed_to_your_group_chat_application);
            // 加群申请被同意
            EMMessage msg = EMMessage
                    .createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new EMTextMessageBody(accepter + " " + st4));
            // 保存同意消息
            //EMChatManager.getInstance().saveMessage(msg);
            EMClient.getInstance().chatManager().sendMessage(msg);
            // 提醒新消息
            HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(msg);

            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    // 刷新ui
                    // if (currentTabIndex == 0)
                    // chatAllHistoryActivity.refresh();
                    if (CommonUtils.getTopActivity(mContext)
                            .equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onRequestToJoinDeclined(String groupId, String groupName,
                                          String decliner, String reason) {
            // 加群申请被拒绝，demo未实现
        }
    }

    private void setListener() {
        mIvContacts.setOnClickListener(this);
        mIvMore.setOnClickListener(this);
    }

    /**
     * 保存提示新消息
     * 
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // 提示有新消息
        HXSDKHelper.getInstance().getNotifier().viberateAndPlayTone(null);
        HXSDKHelper.getInstance().getNotifier().notify();
        // 刷新bottom bar消息未读数
        // updateUnreadAddressLable();
        // 刷新好友页面ui
        // if (currentTabIndex == 1)
        refresh();
    }

    /**
     * 保存邀请等msg
     * 
     * @param msg
     */
    private void saveInviteMsg(InviteMessage msg) {
        // 保存msg
        inviteMessgeDao.saveMessage(msg);
        // 未读数加1
        FriendsUser user = ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                .getContactList().get(Constants.NEW_FRIENDS_USERNAME);
        if (user.getUnreadMsgCount() == 0)
            user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
    }

    void hideSoftKeyboard() {
        if ( getActivity().getWindow()
                .getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if ( getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(
                        getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        // if(((AdapterContextMenuInfo)menuInfo).position > 0){ m,
        getActivity().getMenuInflater().inflate(R.menu.delete_message, menu);
        // }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        boolean handled = false;
        boolean deleteMessage = false;
        if (item.getItemId() == R.id.delete_message) {
            deleteMessage = true;
            handled = true;
        } else if (item.getItemId() == R.id.delete_conversation) {
            deleteMessage = false;
            handled = true;
        }
        EMConversation tobeDeleteCons = adapter.getItem(
                ((AdapterContextMenuInfo) item.getMenuInfo()).position);
        // 删除此会话
        EMClient.getInstance().chatManager().deleteConversation(
                tobeDeleteCons.conversationId(),
                deleteMessage);
        InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(mContext);
        inviteMessgeDao.deleteMessage(tobeDeleteCons.conversationId());
        adapter.remove(tobeDeleteCons);
        adapter.notifyDataSetChanged();

        // 更新消息未读数
        // mContext.updateUnreadLabel();

        return handled ? true : super.onContextItemSelected(item);
    }

    /**
     * 刷新页面
     */
    public void refresh() {
        // Log.e("caijiajun", "i am coming!");
        conversationList.clear();
        conversationList.addAll(loadConversationsWithRecentChat());
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    /**
     * 获取所有会话
     * 
     * @param
     * @return +
     */
    private List<EMConversation> loadConversationsWithRecentChat() {
        // 获取所有会话，包括陌生人
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations(); //获取聊天会话
                // 过滤掉messages size为0的conversation
                /**
                 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
                 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
                 */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    // if(conversation.getType() !=
                    // EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(
                            conversation.getLastMessage().getMsgTime(),
                            conversation));
                    // }
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     * 
     * @param
     */
    private void sortConversationByLastChatTime(
            List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList,
                new Comparator<Pair<Long, EMConversation>>() {
                    @Override
                    public int compare(final Pair<Long, EMConversation> con1,
                            final Pair<Long, EMConversation> con2) {

                        if (con1.first == con2.first) {
                            return 0;
                        } else if (con2.first > con1.first) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }

                });
    }

    /**
     * 连接监听listener
     * 
     */
    public class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
            // 是否与服务器同步
            boolean groupSynced = HXSDKHelper.getInstance()
                    .isGroupsSyncedWithServer();
            boolean contactSynced = HXSDKHelper.getInstance()
                    .isContactsSyncedWithServer();

            // in case group and contact were already synced, we supposed to
            // notify sdk we are ready to receive the events
            if (groupSynced && contactSynced) {
                new Thread() {
                    @Override
                    public void run() {
                        HXSDKHelper.getInstance().notifyForRecevingEvents();
                    }
                }.start();
            } else {
                if (!groupSynced) {
                    asyncFetchGroupsFromServer();
                }

                // 获取通讯录
                if (!contactSynced) {
                    // asyncFetchContactsFromServer();
                    // GetTokenJson mGetTokenJson = new GetTokenJson(
                    // ScreenUtils.getIMEI(mContext),
                    // ScreenUtils.getVersion(mContext),
                    // ScreenUtils.getMobileModelInfo(),
                    // ScreenUtils.getScreenWidth(mContext),
                    // ScreenUtils.getScreenHeight(mContext));
                    // if (LfyApplication.getInstance().getToken().toString()
                    // .equals("")
                    // | LfyApplication.getInstance().getToken()
                    // .toString().equals(null)) {
                    // getTokenRequest(Constant.GETTOKEN_URL, mGetTokenJson);
                    // } else {
                    ContactListJson contactListJson = new ContactListJson(
                            Config.getUserName(),
                            Config.getUserToken());
                    getContactList(Constants.FRIENDSLIST, contactListJson);
                    GetUserJson getUserJson = new GetUserJson(
                            Config.getUserToken(),
                            Config.getUserName());
                    getGroupAvatarRequest(Constants.getAllGroup, getUserJson);
                    // }

                }

                if (!HXSDKHelper.getInstance().isBlackListSyncedWithServer()) {
                    asyncFetchBlackListFromServer();
                }
            }

            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if(Config.isUserLogined())
                    errorItem.setVisibility(View.GONE);
                }

            });
        }

        @Override
        public void onDisconnected(final int error) {
            final String st1 = getResources()
                    .getString(R.string.can_not_connect_chat_server_connection);
            final String st2 = getResources()
                    .getString(R.string.the_current_network);
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        showAccountRemovedDialog();
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登陆dialog
                        showConflictDialog();
                    } else {
                        if(Config.isUserLogined()) {
                            errorItem.setVisibility(View.VISIBLE);
                            if (NetUtils.hasNetwork(mContext))
                                errorText.setText(st1);
                            else
                                errorText.setText(st2);
                        }

                    }
                }

            });
        }
    }

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        DemoHXSDKHelper.getInstance().logout(false, null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!getActivity().isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(
                            getActivity());
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.dismiss();
                                conflictBuilder = null;
                                startActivity(
                                        new Intent(getActivity(),
                                                LoginActivityV2.class));
                            }
                        });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color conflictBuilder error"
                        + e.getMessage());
            }

        }

    }

    static void asyncFetchGroupsFromServer() {
        HXSDKHelper.getInstance().asyncFetchGroupsFromServer(new EMCallBack() {

            @Override
            public void onSuccess() {
                HXSDKHelper.getInstance().noitifyGroupSyncListeners(true);

                if (HXSDKHelper.getInstance().isContactsSyncedWithServer()) {
                    HXSDKHelper.getInstance().notifyForRecevingEvents();
                }
            }

            @Override
            public void onError(int code, String message) {
                HXSDKHelper.getInstance().noitifyGroupSyncListeners(false);
            }

            @Override
            public void onProgress(int progress, String status) {

            }
        });
    }

    static void asyncFetchContactsFromServer() {
        HXSDKHelper.getInstance().asyncFetchContactsFromServer(
                new EMValueCallBack<List<String>>() {

                    @Override
                    public void onSuccess(List<String> usernames) {
                        Context context = HXSDKHelper.getInstance()
                                .getAppContext();

                        System.out.println(
                                "----------------" + usernames.toString());
                        EMLog.d("roster", "contacts size: " + usernames.size());
                        Map<String, FriendsUser> userlist = new HashMap<String, FriendsUser>();
                        for (String username : usernames) {
                            FriendsUser user = new FriendsUser(username);
                            // user.setUsername(username);
                            setUserHearder(username, user);
                            userlist.put(username, user);
                        }
                        // 添加user"申请与通知"
                        FriendsUser newFriends = new FriendsUser(Constants.NEW_FRIENDS_USERNAME);
                        // newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
                        String strChat = context
                                .getString(R.string.Application_and_notify);
                        newFriends.setNickname(strChat);

                        userlist.put(Constants.NEW_FRIENDS_USERNAME, newFriends);
                        // 添加"群聊"
                        FriendsUser groupUser = new FriendsUser(Constants.GROUP_USERNAME);
                        String strGroup = context
                                .getString(R.string.group_chat);
                        //groupUser.setUsername(Constant.GROUP_USERNAME);
                        groupUser.setNickname(strGroup);
                        groupUser.setHeader("");
                        userlist.put(Constants.GROUP_USERNAME, groupUser);

                        // 存入内存
                        ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                .setContactList(userlist);
                        // 存入db
                        UserDao dao = new UserDao(context);
                        List<FriendsUser> users = new ArrayList<FriendsUser>(
                                userlist.values());
                        dao.saveContactList(users);

                        HXSDKHelper.getInstance()
                                .notifyContactsSyncListener(true);

                        if (HXSDKHelper.getInstance()
                                .isGroupsSyncedWithServer()) {
                            HXSDKHelper.getInstance().notifyForRecevingEvents();
                        }

                        ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                .getUserProfileManager()
                                .asyncFetchContactInfosFromServer(usernames,
                                        new EMValueCallBack<List<FriendsUser>>() {

                                            @Override
                                            public void onSuccess(List<FriendsUser> uList) {
                                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                                        .updateContactList(uList);
                                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                                        .getUserProfileManager()
                                                        .notifyContactInfosSyncListener(true);
                                            }

                                            @Override
                                            public void onError(int error, String errorMsg) {
                                            }
                                        });
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        HXSDKHelper.getInstance()
                                .notifyContactsSyncListener(false);
                    }

                });
    }

    static void asyncFetchBlackListFromServer() {
        HXSDKHelper.getInstance().asyncFetchBlackListFromServer(
                new EMValueCallBack<List<String>>() {

                    @Override
                    public void onSuccess(List<String> value) {
                        try {
                            EMClient.getInstance().contactManager().saveBlackList(value);
                        } catch (HyphenateException e) {
                            e.printStackTrace();
                        }
                        HXSDKHelper.getInstance()
                                .notifyBlackListSyncListener(true);
                    }

                    @Override
                    public void onError(int error, String errorMsg) {
                        HXSDKHelper.getInstance()
                                .notifyBlackListSyncListener(false);
                    }

                });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (HXPreferenceUtils.getInstance().getCurrentUserTwo() == null) {
            mGuideViewUtil = new GuideViewUtil( getActivity(), R.drawable.guidance_chat);
            HXPreferenceUtils.getInstance().setCurrentUserTwo("one");
        }
        // register the event listener when enter the foreground
      /*  EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[] {
                        EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage,
                        EMNotifierEvent.Event.EventDeliveryAck,
                        EMNotifierEvent.Event.EventReadAck });*/
        EMClient.getInstance().chatManager().addMessageListener(this);
//        DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper
//                .getInstance();
//        sdkHelper.pushActivity(getActivity());

        if(!Config.isUserLogined()) {
            final String st1 = getResources()
                    .getString(R.string.can_not_connect_chat_server_connection);
            final String st2 = getResources()
                    .getString(R.string.not_login_title);
            errorItem.setVisibility(View.VISIBLE);
            if (NetUtils.hasNetwork(mContext))
                errorText.setText(st2);
            else
                errorText.setText(st1);
        }else{
            errorItem.setVisibility(View.GONE);
        }
        refresh();

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EMClient.getInstance().chatManager().removeMessageListener(this);
//        DemoHXSDKHelper sdkHelper = (DemoHXSDKHelper) DemoHXSDKHelper
//                .getInstance();

        // 把此activity 从foreground activity 列表里移除
        //sdkHelper.popActivity(getActivity());
    }



    // @Override
    // public void onSaveInstanceState(Bundle outState) {
    // super.onSaveInstanceState(outState);
    // if (((MainActivity) getActivity()).isConflict) {
    // outState.putBoolean("isConflict", true);
    // } else if (((MainActivity) getActivity()).getCurrentAccountRemoved()) {
    // outState.putBoolean(Constant.ACCOUNT_REMOVED, true);
    // }
    // }
    private void initBox() {
        // 筛选弹出框
        LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
        mWindowView = layoutInflater.inflate(R.layout.chat_popup_window, null);
        mRlAddGroup = (RelativeLayout) mWindowView
                .findViewById(R.id.rl_chat_add_group);
        mLlAddFriends = (LinearLayout) mWindowView
                .findViewById(R.id.ll_add_friends);
        mLlScan = (LinearLayout) mWindowView.findViewById(R.id.ll_scan);
        // 发起群聊
        mRlAddGroup.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(
                        new Intent(mContext, GroupPickContactsActivity.class)
                                .putExtra("from", "chat"));
                mPopupWindow.dismiss();
            }
        });
        // 添加朋友
        mLlAddFriends.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // AddContactActivity
                Intent intent = new Intent(mContext,
                        AddContactSearchActivity.class);
                startActivity(intent);
                mPopupWindow.dismiss();
            }
        });
        // 扫一扫
        mLlScan.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),
                        CaptureActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SCAN);
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow = new MyPopupWindow(mWindowView,
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, new OnDismiss() {
                    @Override
                    public void onDismiss() {
                        WindowManager.LayoutParams lp = getActivity().getWindow()
                                .getAttributes();
                        lp.alpha = 1f; // 0.0-1.0
                        getActivity().getWindow().setAttributes(lp);
                    }
                });
    }

    private void showWindow(View v) {
        // 使其聚集
        mPopupWindow.setFocusable(true);
        // 设置允许在外点击消失
        mPopupWindow.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 1f; // 0.0-1.0
        getActivity().getWindow().setAttributes(lp);
//        // 计算popupWindow的偏移量
//        DisplayMetrics dm = new DisplayMetrics();
//        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//        int screenWidth = dm.widthPixels;
//        int windowWidth = mPopupWindow.getWidth();
//        int titleWidth = mIvMore.getWidth();
//        Log.i(TAG,
//                "windowWidth" + windowWidth + "---->>>titleWidth" + titleWidth);
//        int xoffInPixels = screenWidth / 2 - titleWidth / 2;
        mPopupWindow.showAsDropDown(v);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode ==  -1) {
            if (data != null) {
                // 解码后的信息
                String content = data.getStringExtra(DECODED_CONTENT_KEY);
                startActivity(
                        new Intent(getActivity(), PersonalDetailsActivity.class)
                                .putExtra("username", content)
                                .putExtra("type", "add"));
            }
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.iv_more:
            if (Config.isUserLogined()) {
                showWindow(v);
            }else{
                startActivity(new Intent(getActivity(),
                        LoginActivityV2.class));
            }
            break;
        case R.id.iv_contacts:
            if (Config.isUserLogined()) {
                Intent contactlistActivity = new Intent(mContext,
                        ContactlistActivity.class);
                startActivity(contactlistActivity);
            }else{
                startActivity(new Intent(getActivity(),
                        LoginActivityV2.class));
            }
            break;
        default:
            break;
        }
    }

    /**
     * 设置hearder属性，方便通讯中对联系人按header分类显示，以及通过右侧ABCD...字母栏快速定位联系人
     * 
     * @param username
     * @param user
     */
    private static void setUserHearder(String username, FriendsUser user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constants.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(
                    HanziToPinyin.getInstance().get(headerName.substring(0, 1))
                            .get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        DemoHXSDKHelper.getInstance().logout(true, null);
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!getActivity().isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(
                            getActivity());
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                dialog.dismiss();
                                accountRemovedBuilder = null;
                                startActivity(
                                        new Intent(getActivity(),
                                                LoginActivityV2.class));
                            }
                        });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
                EMLog.e(TAG, "---------color userRemovedBuilder error"
                        + e.getMessage());
            }

        }

    }
    @Override
    public void onMessageReceived(List<EMMessage> messages) {
//        for(EMMessage message:messages) {
//            // 提示新消息
//            HXSDKHelper.getInstance().getNotifier().onNewMsg(message);
//        }
        refreshUI();
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {

    }

    @Override
    public void onMessageRead(List<EMMessage> messages) {
        refreshUI();
    }

    @Override
    public void onMessageDelivered(List<EMMessage> messages) {
        refreshUI();
    }

    @Override
    public void onMessageChanged(EMMessage message, Object change) {

    }
    private void refreshUI() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                refresh();
            }
        });
    }

    /**
     * 获取好友列表
     * 
     * @param getContactListUrl
     * @param mContactListJson
     */
    public void getContactList(String getContactListUrl,
            ContactListJson mContactListJson) {
        Log.i(TAG, "<loginRequest>--<onResponse>--上传的JSon数据：  LoginJson = "
                + mContactListJson);
        java.lang.reflect.Type type = new TypeToken<BaseResult<List<Friends>>>() {
        }.getType();
        JsonListRequest<BaseResult<List<Friends>>> request = new JsonListRequest<BaseResult<List<Friends>>>(
                mContext, Method.POST, getContactListUrl,
                mContactListJson.toString(), null, null, type, true,
                new Listener<BaseResult<List<Friends>>>() {

                    @Override
                    public void onResponse(BaseResult<List<Friends>> arg0) {
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        List<Friends> data = null;
                        Friends friends = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = arg0.getData();
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<loginRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            // 登陆成功，保存用户名密码
                            if (null != data) {
                                Context context = HXSDKHelper.getInstance()
                                        .getAppContext();
                                Map<String, FriendsUser> userlist = new HashMap<String, FriendsUser>();
                                // 添加user"申请与通知"
                                FriendsUser newFriends = new FriendsUser(Constants.NEW_FRIENDS_USERNAME);
//                                newFriends.setUsername(
//                                        Constant.NEW_FRIENDS_USERNAME);
                                String strChat = context.getString(
                                        R.string.Application_and_notify);
                                newFriends.setNickname(strChat);

                                userlist.put(Constants.NEW_FRIENDS_USERNAME,
                                        newFriends);
                                // 添加"群聊"
                                FriendsUser groupUser = new FriendsUser(Constants.GROUP_USERNAME);
                                String strGroup = context
                                        .getString(R.string.group_chat);
                               // groupUser.setUsername(Constant.GROUP_USERNAME);
                                groupUser.setNickname(strGroup);
                                groupUser.setHeader("");
                                userlist.put(Constants.GROUP_USERNAME,
                                        groupUser);
                                for (int i = 0; i < data.size(); i++) {
                                    String username = data.get(i)
                                            .getFusername();
                                    FriendsUser friendsUser = new FriendsUser(username);
                                    String nick = data.get(i).getFname();
                                    String avatar = Constants.GETIMAGE
                                            + data.get(i).getFimage();
                                   // friendsUser.setUsername(username);
                                    friendsUser.setNickname(nick);
                                    friendsUser.setAvatar(avatar);
                                    setUserHearder(username, friendsUser);
                                    userlist.put(username, friendsUser);
                                    if (nick != null && !nick.equals("")) {
                                        Log.i("nick", nick);
                                    }
                                }
                                // 存入内存
                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                        .setContactList(userlist);
                                // 存入db
                                UserDao dao = new UserDao(mContext);
                                List<FriendsUser> users = new ArrayList<FriendsUser>(
                                        userlist.values());
                                dao.saveContactList(users);
                                HXSDKHelper.getInstance()
                                        .notifyContactsSyncListener(true);

                                if (HXSDKHelper.getInstance()
                                        .isGroupsSyncedWithServer()) {
                                    HXSDKHelper.getInstance()
                                            .notifyForRecevingEvents();
                                }
                                ((DemoHXSDKHelper) HXSDKHelper.getInstance())
                                        .getUserProfileManager()
                                        .notifyContactInfosSyncListener(true);
                                HXSDKHelper.getInstance()
                                        .setisContactsSyncedWithServer();
                            } else {
                                Toast.makeText(mContext, getString(R.string.return_data_null),
                                        Toast.LENGTH_LONG).show();
                            }

                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                        // closeProgressDialog();
                        // hasSendJson = false;
                        adapter.notifyDataSetChanged();
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser.parseCharset(
                                                response.headers));
                                Log.i(TAG,
                                        "<loginRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<loginRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<loginRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null && arg0.toString().contains(
                                "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.ServerError")) {
                            Toast.makeText(mContext,
                                    getString(
                                            R.string.service_temporarily_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<loginRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                        // hasSendJson = false;
                    }

                });
        VolleyUtil.addRequest(request);
    }

    /**
     * 获取群组头像
     * 
     * @param getGroupAvatarUrl
     * @param mGetUserJson
     */
    private void getGroupAvatarRequest(String getGroupAvatarUrl,
            GetUserJson mGetUserJson) {
        Log.i(TAG,
                "<getGroupAvatarRequest>--<onResponse>--上传的JSon数据：  GetTokenJson = "
                        + mGetUserJson);
        java.lang.reflect.Type type = new TypeToken<BaseResult<List<getGroupAvatarByUsernameBean>>>() {
        }.getType();
        JsonListRequest<BaseResult<List<getGroupAvatarByUsernameBean>>> request = new JsonListRequest<BaseResult<List<getGroupAvatarByUsernameBean>>>(
                mContext, Method.POST, getGroupAvatarUrl,
                mGetUserJson.toString(), null, null, type, false,
                new Listener<BaseResult<List<getGroupAvatarByUsernameBean>>>() {

                    @Override
                    public void onResponse(
                            BaseResult<List<getGroupAvatarByUsernameBean>> arg0) {
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        List<getGroupAvatarByUsernameBean> data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = arg0.getData();
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            int size = data.size();
                            if (data != null && size > 0) {
                                // 保存至数据库
                                userDao.saveGroupAvatarList(data);
                            }
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser.parseCharset(
                                                response.headers));
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                                // showToast(mContext, json,
                                // Toast.LENGTH_SHORT);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null && arg0.toString().contains(
                                "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.ServerError")) {
                            Toast.makeText(mContext,
                                    getString(
                                            R.string.service_temporarily_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                    }

                });
        VolleyUtil.addRequest(request);
    }

}
